// 获取catId、goodsId
let catId = lb.getUrlValue('catId');
let goodsId = lb.getUrlValue('goodsId');

// 面包屑导航
let oNowBreadcrumb = document.querySelector('.now-breadcrumb');
oNowBreadcrumb.innerHTML = CAT_DATA.filter(item => item.cat_id == catId)[0].cat_name;

// 商品详情大容器
let oGoodsContent = document.querySelector('.goods-content');
// 猜你喜欢容器
let oGoodsRightContent = document.querySelector('.goods-right-content');

// 请求数据
lb.ajax({
	
	url: BASE_URL + '/api_goods',
	data: {goodsId},
	success(res){
		// console.log(res);
		if(res.code != 0){
			console.log(res);
			return;
		}
		
		// 验证商品有没有
		if(res.data.length == 0){
			oGoodsContent.innerHTML = '此商品已下架...';
			return;
		};

		// 获取商品
		let goods = res.data[0];
		// 放大镜 放大的图
		let goodsBanner = goods.banner;
		// 轮播小图
		let productBanner = goods.product_banner;
		// lc简介
		let lcRecommend = goods.lc_recommend;

		// 面包屑导航中的商品名
		let oNowBreadcrumbName = document.querySelector('.now-breadcrumb-name');
		let str = `<span>${goods.goods_name}</span>`;
		oNowBreadcrumbName.innerHTML = str;

		// 渲染上方右侧商品
		productRightRender(goods);
		
		// 调用放大镜
		zoomRender(goodsBanner);
		
		// 封装小图的轮播
		zoomDownCarousel(goodsBanner);
		
		// 渲染下方详情图
		let oDetailImg = document.querySelector('.detail-img');
		let strDetail = '';
		productBanner.forEach(item => {
			strDetail += `<img src="${item}" />`;
		});
		oDetailImg.innerHTML = strDetail;
		
		// 渲染下方的信息 
		// let oLcRecommendContent = document.querySelector('.lc-recommend-content');
		let oBrandSynopsisContent = document.querySelector('.brand-synopsis-content');
		// let oProductDescriptionContent = document.querySelector('.product-description-content');
		// -lc简介 
		// oLcRecommendContent.innerHTML = `${goods.lc_recommend[4]}`;
		// -品牌简介 
		oBrandSynopsisContent.innerHTML = `${goods.lc_recommend[4]}`;
		// -商品描述
		// oProductDescriptionContent.innerHTML = `${goods.lc_recommend[6]}`;
		
		// 猜你喜欢
		let oChange = document.querySelector('.guess');
	
		// 默认页数和页数商品数
		let page = 1;
		let pagesize = 4;
		
		// 默认调用一次请求数据,DOM渲染
		goodsRender(page, pagesize);
		
		// 点击换一换
		oChange.onclick = function(){
			// console.log("111");
			//加载第2页面
			page ++;
			goodsRender(page, pagesize);
		}
		
	}

});

function goodsRender(page, pagesize){
	// 请求热门商品数据
	lb.ajax({
		url : BASE_URL + '/api_goods',
		data : {page, pagesize},
		success(res){
			console.log(res);
			// 验证
			if(res.code != 0){
				console.log(res);
				return;
			}
			let str_product_goods = '';
			// 遍历组装
			res.data.forEach( item => {
				str_product_goods += `
					<li>
						<a href="product.html?goodsId=${item.goods_id}&catId=${item.cat_id}"><img src="${item.goods_thumb}" alt="" /></a>
						<p>${item.goods_name}</p>
						<p>${item.brand_name}</p>
						<p>￥${item.price}</p>
					</li>
				`;
			});
			oGoodsRightContent.innerHTML = str_product_goods;
		},
	});
};


// 封装小图的轮播
function zoomDownCarousel(data){
	// 获取元素
	let oSmallImg = document.querySelector('.small-img');
	let oBigImg = document.querySelector('.big-img');
	let oZoomDown = document.querySelector('.zoom-down');
	let oZoomDownList = document.querySelector('.zoom-down-list');
	let oNext = document.querySelector('.next');
	let oPrev = document.querySelector('.prev');
	let aLi = document.querySelectorAll('.zoom-down-list li');
	
	// 信号量，确定目前是哪个元素
	let n = 0;
	
	//下一张
	oNext.onclick = rightBtn;
	
	//封装自动播放 和 下一张业务
	function rightBtn(){
		n++;
		//验证 如果是最后一张则返回第一张
		n = n >= aLi.length ? 0 : n;
		//调用方法
		play();	
	};
	
	// 上一张
	oPrev.onclick = function(){
		n--;
		//验证
		n = n < 0 ? aLi.length - 1 : n;
		play();	
	}
	
	// 点击小图, 批量监听
	for(let m = 0; m < data.length; m++){
		//监听事件
		aLi[m].onclick = function(){
			//设置联动
			n = m;
			//调用设置方法
			play();		
		}
		
	};
	
	function play(){
		// 排它
		for(let i = 0; i < aLi.length; i++){
			aLi[i].style.borderColor = '#fff';
		}
		// oZoomDownList.style.left += aLi.length > 5 ? 70*(aLi.length-5) : 0 + 'px';
		aLi[n].style.borderColor = '#000';
		oSmallImg.src = data[n];
		oBigImg.src = data[n];	
	}
};


// 封装渲染右边商品详情的方法
function productRightRender(data){
	let oProductRight = document.querySelector('.product-right');
	let oDesignContent = document.querySelector('.design-content');
	let aLi = document.querySelectorAll('.design-content li');
	
	// 判断款式图片个数
	if(data.banner.length == 1){
		oProductRight.innerHTML = `
			<p class="start"><span class="iconfont icon-aixin_shixin"></span><span>${data.star_number}</span></p>
			<p class="brand">${data.brand_name}</p>
			<p class="goods-name">${data.goods_name}</p>
			<p class="price"><span>价格:</span><span>￥${data.price}</span></p>
			<p><span>免运费</span><span>正品授权</span></p>
			<div>
				<span>款式:</span>
				<ul class="design-content">
					<li><img src="${data.banner[0]}" /></li>
				</ul>
			</div>
			<p><span>数量:</span>
				<img class="reduce" src="img/product-.png" alt="" />
				<span class="goods-count">1</span>
				<img class="add" src="img/product+.png" alt="" />
			</p>
			<button class="now-buy">立即购买</button>
			<button class="add-cart">加入购物车</button>
		`;
	}else if(data.banner.length == 2){
		oProductRight.innerHTML = `
			<p class="start"><span class="iconfont icon-aixin_shixin"></span><span>${data.star_number}</span></p>
			<p class="brand">${data.brand_name}</p>
			<p class="goods-name">${data.goods_name}</p>
			<p class="price"><span>价格:</span><span>￥${data.price}</span></p>
			<p><span>免运费</span><span>正品授权</span></p>
			<div>
				<span>款式:</span>
				<ul class="design-content">
					<li><img src="${data.banner[0]}" /></li>
					<li><img src="${data.banner[1]}" /></li>
				</ul>
			</div>
			<p><span>数量:</span>
				<img class="reduce" src="img/product-.png" alt="" />
				<span class="goods-count">1</span>
				<img class="add" src="img/product+.png" alt="" />
			</p>
			<button class="now-buy">立即购买</button>
			<button class="add-cart">加入购物车</button>
		`;
	}else if(data.banner.length == 3){
		oProductRight.innerHTML = `
			<p class="start"><span class="iconfont icon-aixin_shixin"></span><span>${data.star_number}</span></p>
			<p class="brand">${data.brand_name}</p>
			<p class="goods-name">${data.goods_name}</p>
			<p class="price"><span>价格:</span><span>￥${data.price}</span></p>
			<p><span>免运费</span><span>正品授权</span></p>
			<div>
				<span>款式:</span>
				<ul class="design-content">
					<li><img src="${data.banner[0]}" /></li>
					<li><img src="${data.banner[1]}" /></li>
					<li><img src="${data.banner[2]}" /></li>
				</ul>
			</div>
			<p><span>数量:</span>
				<img class="reduce" src="img/product-.png" alt="" />
				<span class="goods-count">1</span>
				<img class="add" src="img/product+.png" alt="" />
			</p>
			<button class="now-buy">立即购买</button>
			<button class="add-cart">加入购物车</button>
		`;
	}else if(data.banner.length == 4){
		oProductRight.innerHTML = `
			<p class="start"><span class="iconfont icon-aixin_shixin"></span><span>${data.star_number}</span></p>
			<p class="brand">${data.brand_name}</p>
			<p class="goods-name">${data.goods_name}</p>
			<p class="price"><span>价格:</span><span>￥${data.price}</span></p>
			<p><span>免运费</span><span>正品授权</span></p>
			<div>
				<span>款式:</span>
				<ul class="design-content">
					<li><img src="${data.banner[0]}" /></li>
					<li><img src="${data.banner[1]}" /></li>
					<li><img src="${data.banner[2]}" /></li>
					<li><img src="${data.banner[3]}" /></li>
				</ul>
			</div>
			<p><span>数量:</span>
				<img class="reduce" src="img/product-.png" alt="" />
				<span class="goods-count">1</span>
				<img class="add" src="img/product+.png" alt="" />
			</p>
			<button class="now-buy">立即购买</button>
			<button class="add-cart">加入购物车</button>
		`;
	}else if(data.banner.length == 5 || data.banner.length >5){
		oProductRight.innerHTML = `
			<p class="start"><span class="iconfont icon-aixin_shixin"></span><span>${data.star_number}</span></p>
			<p class="brand">${data.brand_name}</p>
			<p class="goods-name">${data.goods_name}</p>
			<p class="price"><span>价格:</span><span>￥${data.price}</span></p>
			<p><span>免运费</span><span>正品授权</span></p>
			<div>
				<span>款式:</span>
				<ul class="design-content">
					<li><img src="${data.banner[0]}" /></li>
					<li><img src="${data.banner[1]}" /></li>
					<li><img src="${data.banner[2]}" /></li>
					<li><img src="${data.banner[3]}" /></li>
					<li><img src="${data.banner[4]}" /></li>
				</ul>
			</div>
			<p><span>数量:</span>
				<img class="reduce" src="img/product-.png" alt="" />
				<span class="goods-count">1</span>
				<img class="add" src="img/product+.png" alt="" />
			</p>
			<button class="now-buy">立即购买</button>
			<button class="add-cart">加入购物车</button>
		`;
	}
	
	// 界面渲染完毕才可以操作加减加车等操作
	// 获取元素
	let oReduce = document.querySelector('.reduce');
	let oAdd = document.querySelector('.add');
	let oGoodsCount = document.querySelector('.goods-count');
	let oNowBuy = document.querySelector('.now-buy');
	let oAddCart = document.querySelector('.add-cart');
	
	let num = 1;
	oGoodsCount.innerHTML = num;
	
	// 点击减
	oReduce.onclick = function(){
		num = --num <=1 ? 1 : num;
		oGoodsCount.innerHTML = num;
	}
	
	// 点击加
	oAdd.onclick = function(){
		num = ++num >= 10 ? 10 : num;
		oGoodsCount.innerHTML = num;
	}
	
	// 点击立即购买
	console.log(oNowBuy);
	oNowBuy.onclick = function(){
		console.log('点击了');
		// 验证是否处于登录状态，未登录情况下先登录
		let USERNAME = localStorage.getItem('username');
		let TOKEN = localStorage.getItem('token');
		// 验证
		if( !USERNAME || !TOKEN){
			alert('未登录，请先登录');
			return;
		}
		
		// 验证通过后加入结算清单，跳转到地址界面
		lb.ajax({
			method : 'post',
			url : BASE_URL + '/api_settlement',
			data : {
				status : 'addsettlement',
				userId : localStorage.getItem('token'),
				from : 'product',
				goodsId,
				goodsNumber : num
			},
			success(res){
				console.log(res);
				if(res.code != 0){
					console.log(res);
					return;
				}
				// 加入成功
				alert('加入结算成功');
				// 跳转到地址页
				location.href = 'address.html';
				
			},
		})
	};
	
	// 点击加入购物车
	oAddCart.onclick = function(){
		// 验证是否处于登录状态，未登录情况下先登录
		let USERNAME = localStorage.getItem('username');
		let TOKEN = localStorage.getItem('token');
		// 验证
		if( !USERNAME || !TOKEN){
			alert('未登录，请先登录');
			return;
		}
		
		// 加入购物车
		lb.ajax({
			method: 'post',
			url: BASE_URL + '/api_cart',
			data: {
				status : 'addcart',
				userId : TOKEN,
				goodsId,
				goodsNumber : num 
			},
			success(res){
				console.log(res);
				if( res.code != 0){
					console.log(res);
					return;
				}
				alert('加入购物车成功！');
				getCartValue();
			}
		});
	};
};

// 放大镜 和放大图片渲染
function zoomRender(data){
	let oProductLeft = document.querySelector('.product-left');
	let oSmallImg = document.querySelector('.small-img');
	let oSlide = document.querySelector('.slide');
	let oZoomUp = document.querySelector('.zoom-up');
	let oZoomBig = document.querySelector('.zoom-big');
	let oBigImg = document.querySelector('.big-img');
	let oZoomDownList = document.querySelector('.zoom-down-list');
	let aLi = document.querySelectorAll('.zoom-down-list li');
	
	
	// 设置默认
	oSmallImg.src = data[0];
	oBigImg.src = data[0];
	
	// 列表
	let str = '';
	data.forEach(item => {
		str += `<li><img src="${item}" alt="" /></li>`;
	});
	// 添加
	oZoomDownList.innerHTML = str;
	
	//一定是上面添加li成功, 设置下面列表宽度
	// let liW = aLi[0].offsetWidth + parseInt(getComputedStyle(aLi[0])['marginRight']);
	// oZoomDownList.style.width = liW * aLi.length + 'px';
	
	// 鼠标移动up
	oZoomUp.onmousemove = function(event){
		// 最终设置的值，先减去滑块的一半, 再减去净位置(元素到浏览器窗口的距离)
		let l = event.clientX - oSlide.offsetWidth/2 - oProductLeft.getBoundingClientRect().left;
		let t = event.clientY - oSlide.offsetWidth/2 - oProductLeft.getBoundingClientRect().top;
			
		//控制范围
		if(l <= 0){l = 0};
		if(t <= 0){t = 0};
		//滑块可以移动最大值
		let maxXY = oZoomUp.clientWidth - oSlide.offsetWidth;
		if(l >= maxXY){l = maxXY};
		if(t >= maxXY){t = maxXY};
			
		//设置滑块
		oSlide.style.left = l + 'px';
		oSlide.style.top = t + 'px';
			
		// console.log(oBigImg.offsetWidth);
		//比例
		let biliXY = (oBigImg.offsetWidth - oZoomBig.clientWidth) / (oZoomUp.clientWidth - oSlide.offsetWidth);
			
		//设置右边大图跟随
		oBigImg.style.left = -l * biliXY + 'px';
		oBigImg.style.top = -t * biliXY  + 'px';
			
	};
		
	// 鼠标移入移出
	oZoomUp.onmouseenter = function(){
		oSlide.style.display = 'block';
		oZoomBig.style.display = 'block';
	};
		
	oZoomUp.onmouseleave = function(){
		oSlide.style.display = 'none';
		oZoomBig.style.display = 'none';
	};
		
	//点击下面列表
	//批量监听
	for(let i = 0; i < aLi.length; i++){
			
		//监听事件
		aLi[i].onclick = function(){
			//拿的到当前点击的元素的  img src 的路径值
			// console.log(this);
			//节点关系
			// console.log(this.firstElementChild.src);
			// console.log(this.firstElementChild.getAttribute('src'));
			let newSrc = this.firstElementChild.getAttribute('src');
			// 设置
			oSmallImg.src = newSrc;
			oBigImg.src = newSrc;
				
			for(let i = 0; i < aLi.length; i++){
				aLi[i].style.borderColor = 'white';
			};
				
			this.style.borderColor = 'orange';
		}
	}
}